<template>
  <div class="svip">
    <head-nav></head-nav>
    <div class="zanwei-top"></div>
    <div class="image vip">
      <div class="vip_card">
        <img id="cardimg" :src="hykimg">
        <!-- <span id="tteexxtt">{{tteexxtt}}</span> -->
        <!-- <canvas style="display:none" id="vipCard"></canvas> -->
      </div>
    </div>
    <div class="fgx"></div>
    <div class="qy jg">
      <ul>
        <li :style="textColor">
          <label>售价</label>
          <span>{{cjhyData.JG}}元</span>
        </li>
      </ul>
    </div>
    <div class="fgx"></div>
    <div class="qy">
      <p>{{cjhyData.HYKMC}}</p>
      <ul>
        <li>
          <label>100元生日券</label>
          <span>{{cjhyData.SRQSL}}张</span>
        </li>
        <li>
          <label>100元购物券</label>
          <span>{{cjhyData.GWQSL}}张</span>
        </li>
        <li>
          <label>每日2小时停车券</label>
          <span>{{cjhyData.TCQSL}}张</span>
        </li>
      </ul>
    </div>

    <div class="fgx"></div>
    <div class="qy">
      <p>积分特权</p>
      <ul>
        <li>
          <label>生日当天</label>
          <span>翻{{cjhyData.SRJF}}倍</span>
        </li>
        <li>
          <label v-html="cjhyData.SJD==undefined?'':cjhyData.SJD.replace(/\|/g,'、')"></label>
          <span>翻{{cjhyData.SJDJF}}倍</span>
        </li>
      </ul>
    </div>

    <div class="fgx"></div>
    <div class="qy" @click="goCjhysm(id)">
      <p>点击查看活动说明</p>
    </div>
    <br>
    <br>
    <br>


    <div class="footbuy" @click="exchangeFn()" :style="backgroundColor">立即抢购</div>

    <!-- 完善信息弹出层 -->
    <div class="zccg" v-show="cgts">
      <div class="zccgbg"></div>

      <div class="zccgbox1">
        <div class="tstitle">请完善信息</div>
        <div class="close" @click="closefn">
          <i class="iconfont icon-close"></i>
        </div>
        <div class="tsms">请您输入正确的身份证信息</div>
        <div class="tscontent">
          <ul>
            <li>
              <mt-field placeholder="请输入您的姓名（必填）" v-model="userlist.name" type="text"></mt-field>
            </li>
            <li>
              <mt-field placeholder="请输入您的身份证号码（必填）"
                        v-model="userlist.idcard"
                        type="text"></mt-field>
            </li>
            <li>
              <mt-field placeholder="请输入您的推荐码（可不填）"
                        v-model="userlist.tjm"
                        ref="tjm"
                        type="number"></mt-field>
            </li>
          </ul>
        </div>
        <div class="zcbtn">
          <mt-button type="primary" size="large" @click.native="wsxxfn()">保存</mt-button>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
  import api from "@/api/api";
  import {MessageBox, Toast, Popup, Indicator} from "mint-ui";
  import {setTimeout} from "timers";

  export default {
    name: "SuperVipIndex",
    data: () => ({
      tteexxtt: "123333",
      cjhyData: {},
      hykimg: "",
      cgts: false,
      userlist: {
        name: "",
        idcard: "",
        address: "",
        tjm: ''
      },
      id: ''
    }),
    watch: {
      'userlist.tjm'(val) {
        if (val.length > 4) {
          let value = val.slice(0, 4);
          this.$refs.tjm.currentValue = value;
          this.userlist.tjm = value;
        }
      }
    },
    methods: {
      goCjhysm(id) {
        this.$router.push('/SuperVipSm/' + id)
      },
      wsxxfn() {
        let page = this;
        let lpsl = this.number;
        let buy = this.buy;
        this.specShow = false;
        console.log(this.userlist.tjm);
        //              (this.userlist.name == "") {
        //                  page.Toastfn("请输入您的姓名",2000);
        //              } else if
        let result = this.$util.checkIDCard(this.userlist.idcard);
        if (!result.status) {
          page.Toastfn(result.msg, 2000);
        } else {
          let fromdata = {
            name: this.userlist.name || "",
            idcard: this.userlist.idcard,
            address: this.userlist.address || ""
          };
          // 更新获取用户信息
          api.updateHyInfo(this, fromdata, function (res) {
            let data = res.data;
            console.log(res);
            if (data.code == 0) {
              console.log("更新成功");
              // Toast({
              //   message: "信息完善成功，您可以购买超级会员了!",
              //   duration: 1200
              // });
              let userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
              payRun(page, userinfo);
              // 关闭完善信息
              page.cgts = false;
            } else {
              page.Toastfn(data.msg, 2000);
            }
          });
        }
      },
      // 提示函数
      Toastfn(message, duration, position) {
        Toast({
          message: message,
          duration: duration,
          position: position
        });
      },
      // 关闭弹出层
      closefn() {
        let page = this;
        page.cgts = false;
      },
      exchangeFn() {
        let that = this;
        let userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
        if (userinfo == null || userinfo.vipcode === "") {
          // 未登录
          Toast({
            message: "您还不是会员，快去注册吧！",
            duration: 1200
          });
          setTimeout(function () {
            //that.$router.push('/register')
            that.$router.push({
              path: "/register",
              query: {
                type: "scoredetail"
              }
            });
          }, 1500);
          return;
        }
        //校验是否可以购买
        Indicator.open("校验用户信息...");
        setTimeout(function () {
          Indicator.close();
          // 查询是否填写了身份证和地址
          that.cgts = true;
        }, randomNum(1, 2000));
      }
    },
    mounted() {
      let id = this.$route.params.id;
      let that = this;
      that.id = id;
      //获取超级会员卡信息
      api.getCjhyInfo(that, id, res => {
        console.log("查询超级会员卡结果", res);
        if (res.data.code == 0) {
          that.cjhyData = res.data.data;
          if (that.cjhyData.CJHYK.length > 0) {
            that.hykimg = that.host.filehost + that.cjhyData.CJHYK[0].ID;
          }
        }
      });
      //加载微信sdk
      api.getWxJsSdkConfig(this, res => {
        console.log(res, "返回结果");
        let data_res = JSON.parse(res.data.data);
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: data_res.appId, // 必填，公众号的唯一标识
          timestamp: data_res.timestamp, // 必填，生成签名的时间戳
          nonceStr: data_res.nonceStr, // 必填，生成签名的随机串
          signature: data_res.signature, // 必填，签名
          jsApiList: ["chooseWXPay"] // 必填，需要使用的JS接口列表
        });
        wx.ready(function () {
          console.log("执行了");
        });
        wx.error(function (res) {
          /* alert(
             "检测到您的支付环境出现问题，无法微信支付，请退出重新进入或者切换网络再试!"
           );*/
        });
      });

    }
  };

  function randomNum(minNum, maxNum) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * minNum + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        break;
      default:
        return 0;
        break;
    }
  }

  function payRun(that, userinfo) {
    api.ckPayStatus(that, that.cjhyData.ID, userinfo.vipcode,that.userlist.tjm, res => {
      if (res.data.code == 0) {
        //可以购买请求微信订单
        Indicator.close();
        Indicator.open("检查支付环境...");
        setTimeout(function () {
          Indicator.close();
          Indicator.open("准备支付...");
          api.saveCjhyPay(
            that,
            that.cjhyData.ID,
            userinfo.vipcode,
            userinfo.openid,
            that.userlist.tjm,
            res => {
              console.log(res, "支付数据");
              let payData = res.data.data;
              wx.chooseWXPay({
                timestamp: payData.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                nonceStr: payData.nonceStr, // 支付签名随机串，不长于 32 位
                package: payData.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                signType: payData.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                paySign: payData.paySign, // 支付签名
                cancel: function (res) {
                  //微信返回的状态 取消:res.errMsg == "chooseWXPay:cancel"
                  Toast({
                    message: "已取消支付",
                    position: "middle",
                    duration: 2000
                  });
                  api.deleteOrderBy(
                    that,
                    payData.orderNo,
                    userinfo.vipcode,
                    that.cjhyData.ID,
                    res => {
                      console.log(res, "取消支付状态");
                    }
                  );
                },
                fail: function (res) {
                  api.deleteOrderBy(
                    that,
                    payData.orderNo,
                    userinfo.vipcode,
                    that.cjhyData.ID,
                    res => {
                      console.log(res, "取消支付状态");
                      Toast({
                        message: "检测到您的支付环境出现问题，无法微信支付，请退出重新进入或者切换网络再试！",
                        position: "middle",
                        duration: 10000
                      });
                    }
                  );
                },
                error: function (res) {
                  //退回上个页面
                  Toast({
                    message: "支付异常",
                    position: "middle",
                    duration: 2000
                  });
                  api.deleteOrderBy(
                    that,
                    payData.orderNo,
                    userinfo.vipcode,
                    that.cjhyData.ID,
                    res => {
                      console.log(res, "取消支付状态");
                    }
                  );
                },
                success: function (res) {
                  /*微信返回的状态 成功:res.errMsg == "chooseWXPay:ok"*/
                  Toast({
                    message: "支付成功",
                    position: "middle",
                    duration: 2000
                  });
                  MessageBox({
                    title: "温馨提示",
                    message: "恭喜您购买成功请到我的钱包查看详情!",
                    showCancelButton: true,
                    showCancelButton: false,
                    confirmButtonText: "确定",
                    closeOnClickModal: false,
                    confirmButtonClass: "zcbtn"
                  }).then(action => {
                    console.log("then");
                    that.$router.push({
                      path: "/wallet"
                    });
                  });
                  //路由到成功页面
                }
              });
            }
          );
        }, randomNum(1, 2000));
      } else {
        MessageBox({
          message: res.data.msg,
          duration: 3000,
          closeOnClickModal: false
        }).then(() => {
          if (res.data.msg === '活动暂未开始！') {
            setTimeout(() => {
              document.getElementsByClassName('msg2')[0].remove();
            }, 200)
          }
        });
        if (res.data.msg === '活动暂未开始！') {
          that.$nextTick(() => {
            let content = document.getElementsByClassName('mint-msgbox-message');
            let msg2 = content[0].getElementsByClassName('msg2');
            if (msg2.length) {
              msg2[0].innerText = '6月21日10点开抢！';
            } else {
              let p = document.createElement('p');
              p.innerText = '6月21日10点开抢！';
              p.className = 'msg2';
              content[0].append(p)
            }
          })
        }
      }
    });
  }
</script>

<style scoped lang="less">
  .svip {
    .vip {
      padding: 0.2rem;

      .vip_card {
        border: 1px solid #eeeeee;
        padding: 0.3rem;
        border-radius: 0.2rem;
        position: relative;
      }
    }

    .fgx {
      height: 0.2rem;
      background-color: #eee;
    }

    .qy {
      padding: 0.2rem;

      p {
        font-weight: bold;
        font-size: 0.3rem;
      }

      ul {
        margin: 0.2rem;
        list-style: none;

        li {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 0.1rem;

          label {
            flex: 14;
          }

          span {
            flex: 3;
          }
        }
      }
    }

    #tteexxtt {
      color: #999;
      font-size: 0.4rem;
      position: absolute;
      left: 1rem;
      bottom: 0.58rem;
    }

    .footbuy {
      position: fixed;
      bottom: 0;
      width: 100%;
      text-align: center;
      background-color: #f05dc4;
      color: #fff;
      height: 48px;
      line-height: 48px;
      font-size: 18px;
    }

    .jg {
      font-weight: bold;
    }
  }

  // 提示
  .zccg {
    width: 100%;
    /*top: 0;*/
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;

    .zccgbox1 {
      // padding-top: 0.7rem;
      position: absolute;
      border-radius: 5px;
      z-index: 10;
      width: 80%;
      /*left: 0;*/
      /*top: 0;*/
      /*right: 0;*/
      /*bottom: 0;*/
      margin: auto;
      // height: 7.5rem;
      /*height: 280px;*/
      background-color: #ffffff;
      // color: #ffffff;
      padding-bottom: .2rem;
      left: 50%;
      transform: translate(-50%, -50%);
      top: 50%;
      text-align: center;
      color: #333333;

      .close {
        position: absolute;
        right: 8px;
        top: 8px;

        .iconfont {
          font-size: 20px;
          color: #666666;
        }
      }

      .tstitle {
        text-align: center;
        font-size: 16px;
        font-weight: bold;
        padding: 12px;
      }

      .tsms {
        font-size: 14px;
        color: #666666;
        padding: 0 20px 10px 20px;
      }

      .tscontent {
        ul {
          li {
            border: 1px solid #e6e6e6;
            margin: 10px;
            border-radius: 5px;
            overflow: hidden;
          }
        }
      }

      .zcbtn {
        margin: 0 10px;
      }
    }

    .zccgbg {
      background-color: #000000;
      position: fixed;
      opacity: 0.5;
      width: 100%;
      height: 100vh;
      top: 0;
      z-index: 9;
    }
  }
</style>
